package com.boe.common.util.freemark.mvc;


import com.boe.common.model.MvcCodeTemplateData;
import lombok.*;
import com.boe.common.util.ScopeUtil;
import com.boe.common.util.freemark.BaseMethodModelFreemarker;
import com.boe.common.util.freemark.ContextMapScope;
import com.boe.common.util.freemark.P0Error;
import freemarker.template.TemplateModelException;

import java.util.List;

/**
 * 当前上下文实体是否有指定的字段。
 */
public class FreemarkerHas extends BaseMethodModelFreemarker {

    @Override
    public Object exec(List list) throws TemplateModelException {
        var paramValue = getFreemarkerParameter(list.get(0));
        if (paramValue instanceof String) {
            var model = ScopeUtil.getScopes().getLatest(ContextMapScope.class).getValue();
            var fields = ((MvcCodeTemplateData) model).getFields();

            return fields.stream().anyMatch(it -> it.getName().equals(paramValue));
        }

        throw new P0Error(paramValue);
    }
}